package com.ybkj.daijia.server.event.listener;

import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.server.event.model.DjxNoticeEvent;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.DjInsurance;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.SmsTemplet;
import com.ybkj.daijia.server.model.SmsTemplet.SmsType;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.SmsService;
import com.ybkj.daijia.server.service.SmsTempletService;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class DjxNoticeEventListener implements ApplicationListener<DjxNoticeEvent> {

    private static final Logger logger = LoggerFactory.getLogger(DjxNoticeEventListener.class);

    @Autowired
    private SmsTempletService smsTempletService;
    @Autowired
    private SmsService smsService;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private CompanyService companyService;

    @Override
    @Async
    public void onApplicationEvent(DjxNoticeEvent event) {
        Driver driver = (Driver) event.getSource();
        DjInsurance djInsurance = event.getDjInsurance();

        int ret = -99;
        try {
            SmsTemplet templet = smsService.findByAlias(driver.getCompanyId(), SmsType.djxNotice);
            Company driverCompany = companyService.findOne(driver.getCompanyId());
            Company finalCompany = driverCompany;
            Company main = companyService.getMain();
            Setting setting = settingUtils.get();
            if (!main.getId().equals(driverCompany.getId()) && setting.isSmsMainCompany()) {
                finalCompany = main;
            }
            if (null != templet && StringUtils.isNotBlank(templet.getContent())) {
                String createdStr = new SimpleDateFormat("yyyy-MM-dd HH:mm")
                    .format(djInsurance.getCreated());
                ret = smsService.sendSms(driver.getPhone(), "djxNotice",
                    "{\"订单号\":\"" + "***" + djInsurance.getOrderNo().substring(8) + "\",\"保险时间\":\""
                        + createdStr + "" + "\",\"保险金额\":\"" + djInsurance.getMoney()
                        .setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "\"}",
                    finalCompany.getId(), 0, finalCompany.getSignName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.debug("短信结果：" + ret);
    }

}
